'use client'
import Add from 'public/icons/user/add.svg'
import styles from './Tag.module.scss'
import { useRef, useState,useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { cFetch } from '@/lib/Http'
export default function(props:{
  kind: TagType,
  setCurTag: (id: number) => void
}){
  const [tagArr, setTagArr] = useState([] as Tag[])
  const page = useRef(0)
  const hasMore = useRef(false)
  type Fetcher = () => Promise<Resources<Tag>>
  const fetcher: Fetcher = () => {
    return cFetch.get<Resources<Tag>>(
      '/tag/group',
      { kind: props.kind, page: page.current + 1 },
      { _autoLoading: true }
    )
  }
  const fetchTags = async () => {
    const response = await fetcher()
    const { resources, pager } = response
    setTagArr(resources)
    hasMore.current = (pager.page - 1) * pager.per_page + resources.length < pager.count
    page.current += 1
  }
  useEffect(() => {
    fetchTags()
  },[])

  const chosenTag = useRef<Tag|null>(null)
  const isActive = (tag: Tag) => {
    const state =  tag.id === chosenTag.current?.id
    return state ? styles.active : ''
  }
  const router = useRouter()
  const addNewTag = () => {
    router.push(`/tagPage/create?kind=${props.kind}`)
  }

  const handleClickTag = (tag:Tag) => {
    chosenTag.current = tag
    props.setCurTag(tag.id)
  }

  const currentTag = useRef<HTMLDivElement>()
  const timer = useRef<NodeJS.Timeout>();
  const startTouchTag = (e: React.TouchEvent, tag: Tag) => {
    currentTag.current = e.target as HTMLDivElement
    timer.current = setTimeout(() => {
      router.push(`/tagPage/${tag.id}/edit?kind=${tag.kind}`)
    }, 500)
  }
  const endTouchTag = () => {
    clearTimeout(timer.current)
  }
  const handleTouchmove = (e: React.TouchEvent) => {
    const touchEle = document.elementFromPoint(e.touches[0].clientX, e.touches[0].clientY)
    if (currentTag.current !== touchEle && currentTag.current?.contains(touchEle) === false) {
      clearTimeout(timer.current)
    }
  }
  return (
    <div className={styles.tagsWrap}>
      <ul onTouchMove={handleTouchmove}>
        <li onClick={addNewTag}>
          <span className={[styles.emojiWrap, styles.addIcon].join(' ')}><Add/></span>
          <span className={styles.emojiName}>新增</span>
        </li>
        {
          tagArr.map((tag: any) => (
            <li key={tag.id}
              onClick={()=>handleClickTag(tag)}
              onTouchStart={(e)=>{startTouchTag(e, tag)}}
              onTouchEnd={endTouchTag}>
              <span className={[styles.emojiWrap, isActive(tag)].join(' ')}>{ tag.sign }</span>
              <span className={styles.emojiName}>{ tag.name.slice(0, 4) }</span>
            </li>
          ))
        }
        <p className="bottomFuncRow">
          { hasMore && <span>显示更多</span>}
        </p>
      </ul>
    </div>
  )
}